/*****************************************************************************
 *   Copyright 2005 Tim A Wang
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 ****************************************************************************/
package com.jb.web.renderer;

import com.jb.web.bean.Link;
import com.jb.web.bean.Text;
import com.jb.web.context.WebContext;

import com.jb.faces.component.UIComponent;


public class LinkRenderer extends TextRenderer {
    public StringBuffer render(WebContext pCtx, UIComponent itemToRender) {
        StringBuffer html = new StringBuffer();
        Link hItem = (Link) itemToRender;

        if (!isVisible(pCtx, hItem)) {
            return html;
        }

        Object value = getValue(pCtx, hItem);

        if (value != null) {
            html.append(value);
        } else {
            html.append("&nbsp;");
        }

        return html;
    }

    protected String getURL(WebContext pCtx, Link hItem) {
        String dest = hItem.getDestination();

        if (isEmptyString(dest)) {
            dest = "${context.pageName}.xsp";
        }

        String url = (String) evaluate(pCtx, hItem, dest);

        if (!url.startsWith("javascript:")) {
            url = pCtx.formURL(url, hItem);
        }

        if (isEditable(pCtx, hItem)) {
            url = "";
        }

        return url;
    }

    protected String getValue(WebContext pCtx, Text itemToRender) {
        Link hItem = (Link) itemToRender;
        String value = super.getValue(pCtx, itemToRender);

        return renderALink(pCtx, hItem, value);
    }

    protected String renderALink(WebContext pCtx, Link hItem, String value) {
        StringBuffer sb = new StringBuffer("<a ");
        String url = getURL(pCtx, hItem);
        String desc = (String) evaluate(pCtx, hItem, hItem.getTitle());
        sb.append(getEditScript(pCtx, hItem)).append(addTagProperty("style", hItem.getStyle(pCtx), null))
          .append(addTagProperty("class", hItem.getStyleClass(), null)).append(addTagProperty("href", url, null))
          .append(addTagProperty("title", desc, null)).append(" >").append(value).append("</a> ");

        return sb.toString();
    }
}
